import React, {Component} from 'react'
import Taro from '@tarojs/taro'
import {View, Textarea, Button} from '@tarojs/components'
import {AtImagePicker, AtRadio} from 'taro-ui'
import {getStorageSync, showToast, throttle} from '../../utils/common'
import {createDy} from '../../service/dynamic'
import './index.scss'


class ReleaseDynamic extends Component {
  state: any = {
    userID: '',
    category: 0, // 0日常1学习2失物招领
    user_picture: '',
    user_name: '',
    files: [],
    upLoadImg: [],
    content: '',
    isShoWAdd: true
  }

  componentDidMount() {
    this.loadData()
  }

  loadData() {
    let {id, user_picture,user_name} = getStorageSync('userInfo')
    if (!id) {
      showToast('请先登录！')
      return Taro.switchTab({
        url: '/pages/user/user'
      })
    } else {
      this.setState({
          userID: id,
          user_picture: user_picture,
          user_name:user_name
        }
      )
    }
  }

  v

  // 分类选择
  handleChangeOption = (v: number) => {
    this.setState({
      category: v
    })
  }

  // 选择图片
  HandleOnChangeImg(v) {// doType代表操作类型，移除图片和添加图片,index为移除图片时返回的图片下标


    this.setState({
      files: v
    })
    if(this.state.files.length ===3 ){
      this.setState({
        isShoWAdd: false
      })
    } else {
      this.setState({
        isShoWAdd: true
      })
    }
  }

  // 文字赋值
  saveText = (v) => {
    this.setState({
      content: v.detail.value
    })
  }

  //上传失败事件
  HandleOnFailImg(mes) {
    console.log(mes)
  }


  //图片被点击事件
  HandleOnImageClick(index) {
    let imgs: any = []
    this.state.files.map((item: any) => {
      return imgs.push(item.file.path)
    })

    Taro.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })

  }

  //发布提交事件
  toUpload = async () => {
    Taro.showLoading({
      title: '正在发布'
    })
    const {files, upLoadImg, content, userID, user_picture,user_name, category} = this.state;
    if (!content) return showToast('文字内容不能为空！');
    if (files.length > 0) {
      console.log(1);
      try {
        const rootUrl = 'https://ugjvtq.top'; // 服务器地址
        await this.uploadLoader({rootUrl, path: files});
        let params = {
          user_id: userID,
          user_name:user_name,
          user_picture: user_picture,
          dy_img: JSON.stringify(upLoadImg),
          dy_content: content,
          dy_category: category
        }
        const res = await createDy(params)
        Taro.hideLoading()
        // console.log(res);
        if (res.code === 1) {
          Taro.showToast({
            title: '发布成功！',
            icon: 'none',
            duration: 2000
          })
          Taro.navigateBack({
            delta: 1
          })
        }
      } catch (e) {
        Taro.hideLoading()
        console.log(e);
        showToast('发布失败！')
      }

      // const cookieData = Taro.getStorageSync('token')  // 图片上传需要单独写入token

    } else {
      console.log(2);
      console.log(content);
      console.log(userID, user_picture);
      let params = {
        user_id: userID,
        user_name:user_name,
        user_picture: user_picture,
        dy_content: content,
        dy_category: category
      }
      try {
        const res = await createDy(params)
        Taro.hideLoading()
        if (res.code === 1) {
          Taro.showToast({
            title: '发布成功！',
            icon: 'none',
            duration: 2000
          })
          Taro.navigateBack({
            delta: 1
          })
        }

      } catch (e) {
        Taro.hideLoading()
        showToast('发布失败！')
      }
      // Taro.showToast({
      //   title: '请先点击+号选择图片',
      //   icon: 'none',
      //   duration: 2000
      // })
    }
  }

  // 上传图片组件
  uploadLoader = (data) => {
    let that = this
    return new Promise(((resolve, reject) => {

      function LoadUPIMG() {
        let i = data.i ? data.i : 0 // 当前所上传的图片位置
        let success = data.success ? data.success : 0//上传成功的个数
        let fail = data.fail ? data.fail : 0;//上传失败的个数
        Taro.showLoading({
          title: `正在上传第${i + 1}张图片`
        })
        //发起上传
        Taro.uploadFile({
          url: data.rootUrl + '/server/upload',
          header: {
            'content-type': 'multipart/form-data',
          },
          name: 'file',
          filePath: data.path[i].url,
          success: (resp) => {
            //图片上传成功，图片上传成功的变量+1
            let resultData = JSON.parse(resp.data)
            if (resultData.code === 1) {
              success++;
              that.setState((prevState: any) => {
                let oldUpload = prevState.upLoadImg
                oldUpload.push(resultData.filename)
                return ({
                  upLoadImg: oldUpload
                })
              }, () => {
                // setSate会合并所有的setState操作，所以在这里等待图片传完之后再调用设置url方法
                /*
                * 该处十分重要
                **/
                //this.setFatherUploadSrc()// 设置数据图片地址字段
              })
            } else {
              fail++;
            }
          },
          fail: () => {
            fail++;//图片上传失败，图片上传失败的变量+1
            reject()
          },
          complete: async () => {
            Taro.hideLoading()
            i++;//这个图片执行完上传后，开始上传下一张
            if (i == data.path.length) {   //当图片传完时，停止调用
              console.log(that.state.upLoadImg)
              console.log(that.state.content)
              console.log('成功：' + success + " 失败：" + fail);
              resolve()
            } else {
              //若图片还没有传完，则继续调用函数
              data.i = i;
              data.success = success;
              data.fail = fail;
              LoadUPIMG();
            }
          }
        })
      }

      LoadUPIMG()
    }))

  }


  render() {
    return (
      <View className='release_main'>
        <Textarea
          className='rel_text'
          maxlength={240}
          onInput={throttle(this.saveText, 50)}
          placeholder='输入文字内容...' autoFocus
        />
        <View className='rel_opt'>
          <View className='rel_ra_title'>内容分类:</View>
          <AtRadio
            options={[
              {label: '日常闲聊', value: 0},
              {label: '学习打卡', value: 1},
              {label: '失物招领', value: 2}
            ]}
            value={this.state.category}
            onClick={this.handleChangeOption.bind(this)}
          />
        </View>

        <View className='rel_img'>
          <View className='rel_title'>图片上传:</View>
          <View className='rel_img_num'>
            <AtImagePicker
              length={2}
              count={3}
              files={this.state.files}
              showAddBtn={this.state.isShoWAdd}
              onChange={this.HandleOnChangeImg.bind(this)}
              onFail={this.HandleOnFailImg.bind(this)}
              onImageClick={this.HandleOnImageClick.bind(this)}
            />
          </View>
          <Button
            type='primary'
            className='poof_submit_btn'
            onClick={throttle(this.toUpload, 1000)}
          >发表动态</Button>
        </View>
      </View>
    )
  }
}

export default ReleaseDynamic
